<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <form action="http://localhost:8001/submit" method="post" id="J_form">
      <p>
        Username: <input type="text" id="J_username" placeholder="Username" />
      </p>
      <p>
        Password:
        <input type="password" id="J_password" placeholder="Password" />
      </p>
      <p>
        <input type="submit" id="J_submit" value="Submit" />
      </p>
    </form>
  </body>
  <script>
    var oUsername = document.getElementById('J_username'),
      oPassword = document.getElementById('J_password'),
      oSubmitBtn = document.getElementById('J_submit'),
      submitUrl = document.getElementById('J_form').action;

    oSubmitBtn.onclick = function (e) {
      e.preventDefault();

      var username = oUsername.value,
        password = oPassword.value;

      //添加前端表单校验规则
      if (username.length < 6 || username.length > 20) {
        alert('username: 6-20');
        return;
      }

      if (password.length < 6 || password.length > 10) {
        alert('password: 6-10');
        return;
      }

      //向服务器提交表单信息
      fetch('http://127.0.0.1:8001/submit', {
        method: 'post',
        body: JSON.stringify({
          username,
          password
        }),
        headers: {
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then((res) => console.log(res));
    };
  </script>
</html>
